package socketdemo.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * @author zoush
 * @createTime 2024/12/04  15:06
 */
public class ChatHandlerDemo implements Runnable {
    private ChatServerDemo chatServerDemo;
    private Socket socket;

    public ChatHandlerDemo(ChatServerDemo chatServerDemo, Socket socket) {
        this.chatServerDemo = chatServerDemo;
        this.socket = socket;
    }


    @Override
    public void run() {
        try {
            chatServerDemo.addClient(socket);
            //读取客户端发送的消息
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String msg = null;
            while ((msg = bufferedReader.readLine()) != null) {
                String sendmsg = "Client[" + socket.getPort() + "]:" + msg;
                System.out.println("客户端发送的消息：" + sendmsg);
                chatServerDemo.sendMessage(socket, sendmsg + "\n");
                if (msg.equals("quit")) {
                    break;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                chatServerDemo.removeClient(socket);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
